<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_services_TagService extends f_core_Service
{
	/**
	 * @var m_backoffice_services_TagService
	 */
	private static $instance;
	
	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}
	
	/**
	 * @return m_backoffice_services_TagService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
		
	/**
	 * Save the tag for the document
	 * @param $document
	 * @param $tag
	 */
	public function saveTagForDocument($document, $tagName, $lang = null)
	{
		$docId = $document->getUniqueId();
		$docLang = $document->getLang();
		$tag = $this->getTagByName($tagName);
		
		if(is_null($lang)) $lang = $this->getContextLang();
		
		if(empty($tag) == true)
		{
			$tag = m_backoffice_documents_Tag::createNew();
			$tag->setAuthor($this->getUser()->getLogin())->setLabel($tagName)->setLang($lang)->save();
		}

		$currentTags = $tag->getDocId();
		$newTags = $currentTags . "{".$docId.",".$docLang."}";
		
		if(!preg_match("/(".$docId.",".$docLang.")/", $currentTags))
		{
			$tag->setLang($lang)->setDocId($newTags)->save();
		}
		
		return $tag;
	}
	
	/**
	 * Delete de tag for a document
	 * @param $docId
	 * @param $docLang
	 * @param $tag
	 */
	public function deleteTagForDocument($docId, $docLang, $tag)
	{
		$docIds = $tag->getDocId();
		$tabDocIds = explode("{", $docIds);
		$tabId = array_search($docId.",".$docLang."}",$tabDocIds);

		if(!empty($tabId))
		{
			unset($tabDocIds[$tabId]);

			if(count($tabDocIds) == 1)
			{
				$tag->deleteRecursive();
			}
			else
			{
				$tag->setDocId(join("{",$tabDocIds))->save();
			}
		}
	}
	
	/**
	 * Retrieve all tag
	 *
	 * @return array
	 */
	public function getAllTag()
	{	
		return $this->getDocumentProvider()->loadDocuments("modules_backoffice/tag")->retrieveDocuments();
	}
	
	/**
	 * Retrieve tag by lang
	 * @param lang
	 * @return array
	 */
	public function getTagByLang($lang)
	{	
		return $this->getDocumentProvider()->loadDocuments("modules_backoffice/tag")->retrieveDocuments($lang);
	}
	
	/**
	 * Retrieve tag by name
	 * @param name
	 * @return tagDocument
	 */
	public function getTagByName($name)
	{		
		return $this->getDocumentProvider()->loadDocuments("modules_backoffice/tag")->whereIsEqual("document_label", $name)->retrieveFirstDocument();
	}
	
	/**
	 * Get tree root node for a given module name
	 * @param $documentId
	 * @param $lang
	 * @return array
	 */
	public function getTagByDocId($docId, $lang = null)
	{
		if(is_null($lang)) $lang = $this->getContextLang();

		return $this->getDocumentProvider()->loadDocuments("modules_backoffice/tag")->whereLike("docId", "%{".$docId.",".$lang."}%")->retrieveDocuments();
	}
	
	public function getDocByTagName($tagName, $parentDoc = null)
	{
		$docs = Array();
		$tag = $this->getTagByName($tagName);
		
		if($tag)
		{
			$tabDocIds = explode("{",$tag->getDocId());
			foreach($tabDocIds as $DocIds)
			{
				preg_match("/([0-9]+),([A-Z]{2})/", $DocIds, $matches);
				if(!empty($matches))
				{
					$doc = $this->getDocumentProvider()->getByUniqueId($matches[1], $matches[2]);
					if(!is_null($parentDoc))
					{
						$relationManager = f_relation_Manager::getInstance();

                        $parents = $relationManager->getParentsIdsByDocType($doc->getUniqueId(), $parentDoc->getModel(), $parentDoc->getLang());

                        foreach($parents as $parent)
                        {
                            if($parent["parent_id"] == $parentDoc->getUniqueId())
                            {
                                $docs[] = $doc;
                            }
						}
					}
					else
					{
						$docs[] = $doc;
					}
				}
			}
		}
		
		return $docs;
	}
}